package com.mfoyou.agent.web.controller.order;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.mfoyou.agent.common.dao.domain.HuawuOrderLog;
import org.mfoyou.agent.common.dao.domain.HuawuPay;
import org.mfoyou.agent.common.dao.domain.HuawuServiceCoupon;
import org.mfoyou.agent.common.dao.domain.HuawuServiceOrder;
import org.mfoyou.agent.common.dao.domain.HuawuServiceUserCoupon;
import org.mfoyou.agent.common.dao.domain.HuawuWorker;
import org.mfoyou.agent.common.dao.mfoyou.domain.MfoyouGoodsOrder;
import org.mfoyou.agent.common.entity.MfoyouCommonUtil;
import org.mfoyou.agent.common.entity.enums.CommonState;
import org.mfoyou.agent.common.entity.enums.MfoyouUserType;
import org.mfoyou.agent.common.entity.enums.OrderState;
import org.mfoyou.agent.common.entity.enums.OrderType;
import org.mfoyou.agent.common.entity.enums.PayType;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.IOrder;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.common.DateUtils;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.ListObject;
import org.mfoyou.agent.utils.common.Logger;
import org.mfoyou.agent.utils.common.MfoyouEncrypt;
import org.mfoyou.agent.utils.common.ObjectUtil;
import org.mfoyou.agent.utils.common.StrUtil;
import org.mfoyou.agent.utils.common.StringUtils;
import org.mfoyou.agent.utils.json.JSONMaker;
import org.mfoyou.agent.utils.json.Json2Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.account.RunnerService;
import com.mfoyou.agent.web.service.common.GeoService;
import com.mfoyou.agent.web.service.order.PaymentService;
import com.mfoyou.agent.web.service.order.ServiceOrderService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.service.wx.WXBaseService;
import com.mfoyou.agent.web.utils.common.PriceData;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;

/**
 * 订单接口类
 *
 * @author wb-zh270168
 */
@Path("/order/service")
@Service
public class ServiceOrderController {

    private static final Logger logger = Logger.getLogger(ServiceOrderController.class);

    public static final String SERVICE_ORDER_REVOKE = "xp:Line9";

    @Autowired
    SessionService sessionService;

    @Autowired
    ServiceOrderService serviceOrderService;

    @Autowired
    RunnerService runnerService;

    @Autowired
    IOrder iOrder;

    @Autowired
    GeoService geoService;

    @Autowired
    PaymentService paymentService;

    @Autowired
    WXBaseService wxBaseService;

    @Autowired
    IAccount iAccount;

    @Autowired
    RedisCacheManger redisCacheManger;

    /**
     * 用户下单接口
     *
     * @param request
     * @param response
     * @param agentId
     * @param json
     * @return
     */
    @POST
    @Path(value = "/add/serviceOrder/{agentId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> addOrder(@Context HttpServletRequest request, @Context HttpServletResponse response,
                               @PathParam("agentId") Integer agentId, String json) {
        HuawuServiceOrder huawuServiceOrder = Json2Object.json2Object(json, HuawuServiceOrder.class);
        huawuServiceOrder.setServiceOrderSendUser(sessionService.currentUserId(request));
        huawuServiceOrder.setServiceOrderState(OrderState.emOpenOrder.getValue());
        huawuServiceOrder.setServiceOrderCreateTime(null);
        huawuServiceOrder.setServiceOrderModifyTime(null);
        huawuServiceOrder.setServiceOrderId(null);
        huawuServiceOrder.setServiceOrderSmallType(2);
        int ret = serviceOrderService.checkMfoyouOrder(huawuServiceOrder, 1);
        if (ret != 0) {
            return JsonRet.buildRet(ret);
        }

        // 插入订单记录 - 并通知跑腿儿小哥
        huawuServiceOrder = serviceOrderService.addServiceOrder(huawuServiceOrder);
        if (huawuServiceOrder != null) {
            // 该订单用户是否使用优惠券
            Integer touchId = huawuServiceOrder.getTouchId();
            if (touchId != null) {
                // 使用了优惠券更新优惠券状态为已使用
                HuawuServiceUserCoupon huawuServiceUserCoupon = new HuawuServiceUserCoupon();
                huawuServiceUserCoupon.setTouchId(touchId);
                huawuServiceUserCoupon.setReduceAmount(huawuServiceOrder.getCouponReduceMoney());
                huawuServiceUserCoupon.setUseTime(new Date());
                huawuServiceUserCoupon.setOrderId(huawuServiceOrder.getServiceOrderId());
                huawuServiceUserCoupon.setTouchState(0);
                serviceOrderService.updateCoupon(huawuServiceUserCoupon);
            }

            return JsonRet.buildSuccRet(huawuServiceOrder);
        } else {
            return JsonRet.buildRet(-1);
        }
    }

    /**
     * 追加附加費
     *
     * @param request
     * @param response
     * @param orderId
     * @param amount
     * @return
     */
    @POST
    @Path(value = "/additional/order/{orderId}/{amount}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> additionalTip(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("orderId") Integer orderId, @PathParam("amount") Integer amount) {
        HuawuServiceOrder mfoyouServiceOrder = serviceOrderService.getServiceOrderInfo(orderId);
        if (mfoyouServiceOrder == null || (mfoyouServiceOrder.getServiceOrderState() >= OrderState.emRunerAccept.getValue())
                || (!sessionService.currentUserId(request).equals(mfoyouServiceOrder.getServiceOrderSendUser()))) {
            return JsonRet.buildRet(-95);
        }
        if (amount == null || amount <= 0) {
            return JsonRet.buildRet(-14);
        }
        HuawuServiceOrder checkServiceOrder = new HuawuServiceOrder();
        HuawuServiceOrder updateServiceOrder = new HuawuServiceOrder();
        checkServiceOrder.setServiceOrderId(orderId);
        checkServiceOrder.setServiceOrderAttachAmount(mfoyouServiceOrder.getServiceOrderAttachAmount());
        checkServiceOrder.setServiceOrderState(mfoyouServiceOrder.getServiceOrderState());
        updateServiceOrder.setServiceOrderAttachAmount(mfoyouServiceOrder.getServiceOrderAttachAmount() + amount);
        updateServiceOrder.setServiceOrderState(OrderState.emPayingOrder.getValue());
        updateServiceOrder.setServiceOrderAmount(mfoyouServiceOrder.getServiceOrderAmount() + amount);
        if (serviceOrderService.updateServiceOrderState(checkServiceOrder, updateServiceOrder, sessionService.currentUserId(request))) {
            return JsonRet.buildRet(0);
        } else {
            return JsonRet.buildRet(-15);
        }
    }

    /**
     * 普通用户订单列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param serviceOrderType
     * @param serviceTagId
     * @param smallType
     * @param serviceOrderState
     * @param orderBy
     * @param orderSource
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/my/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> myList(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
                             @QueryParam("type") Integer serviceOrderType, @QueryParam("tagId") Integer serviceTagId, @QueryParam("smalltype") Integer smallType,
                             @QueryParam("state") Integer[] serviceOrderState, @QueryParam("orderby") Integer orderBy, @QueryParam("orderSource") Integer orderSource) {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderSendUser(sessionService.currentUserId(request));
        mfoyouServiceOrder.setServiceOrderType(serviceOrderType);
        mfoyouServiceOrder.setServiceTagId(serviceTagId);
        mfoyouServiceOrder.setServiceOrderSmallType(smallType);
        if (sessionService.currentUserType(request).intValue() == UserRight.STOREACCESS.getValue()) {
            mfoyouServiceOrder.setServiceOrderSource(3);
        } else {
            if (orderSource == null || orderSource == 0) {
                mfoyouServiceOrder.setServiceOrderSource(0);
            } else {
                mfoyouServiceOrder.setServiceOrderSource(2);
            }
        }
        mfoyouServiceOrder.setAgentId(sessionService.currentUserAgentId(request));
        Date startDate = DateUtils.parse(request.getParameter("startDate"));
        Date endDate = DateUtils.parse(request.getParameter("endDate"));
        ArrayListObject<HuawuServiceOrder> listObject = serviceOrderService.getServiceOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, ObjectUtil.arrary2List(serviceOrderState),
                orderBy);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(
                serviceOrderService.attachWorkUserInfo(listObject, new String[]{"userName", "userHeadUrl", "userPhone", "workerCommentCount", "workerName", "workerPhone", "workerStar", "userNickName"})));
    }

    /**
     * 动态调用接口计算费用接口
     *
     * @param request
     * @param response
     * @param distance         距离
     * @param weight           重量
     * @param hour             时间
     * @param serviceOrderType 订单类型[1-帮我取, 2-帮我送, 3-帮我买, 4-帮我做, 29-拉货]
     * @param lon              经度
     * @param lat              纬度
     * @param tagId            标签id
     * @param dt               指定时间- 不传默认使用当前时间点为起点进行费用计算
     * @param agentStr         1=顾客，2=代理商，4=跑腿员，8=商家 16=商家服务商 128=总管理
     * @param tagName          标签名称[钥匙, 快递]
     * @param touchId          优惠券id
     * @param typeName         优惠券名称 eg: 帮我做
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/priceV2")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> servicePriceV2(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("distance") Integer distance,
                                     @QueryParam("weight") Integer weight, @QueryParam("hour") Integer hour, @QueryParam("type") Integer serviceOrderType,
                                     @QueryParam("lon") Double lon, @QueryParam("lat") Double lat, @QueryParam("tagId") Integer tagId, @QueryParam("dt") Long dt,
                                     @QueryParam("agentStr") String agentStr, @QueryParam("tagName") String tagName, @QueryParam("touchId") Integer touchId,
                                     @QueryParam("typeName") String typeName) {
        if (serviceOrderType == null || agentStr == null) {
            return JsonRet.buildRet(-96);
        }

        // 计算时间
        Date time = dt == null ? new Date() : new Date(dt);

        // 解码代理商id
        Integer agentId = MfoyouEncrypt.decode(agentStr);

        // 距离 重量判断
        if (distance == null) {
            distance = 0;
        }
        if (weight == null) {
            weight = 0;
        }

        Integer userId = sessionService.currentUserId(request);
        logger.info(String.format("servicePriceV2  获取userId=[%s], serviceOrderService=[%s]", userId, serviceOrderService));

        // 计算价格
        PriceData calOrderPriceV2 = serviceOrderService.calOrderPriceV2(agentId, serviceOrderType, weight, distance, hour, tagName, time, touchId, typeName, userId, false);

        // 返回数据判断
        if (calOrderPriceV2 == null) {
            return JsonRet.buildRet(-2999);
        }
        return JsonRet.buildSuccRet(calOrderPriceV2);
    }

    /**
     * 查看订单详情
     *
     * @param request
     * @param response
     * @param orderId
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/info")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> orderInfo(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("orderId") Integer orderId) throws ParseException {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        Integer userType = sessionService.currentUserType(request);
        if (userType == 1 || userType == 8) {
            mfoyouServiceOrder.setServiceOrderSendUser(sessionService.currentUserId(request));
        } else if (userType == 4) {
            mfoyouServiceOrder.setServiceOrderReceiveUser(sessionService.currentUserId(request));
        } else if (userType == 2) {
            mfoyouServiceOrder.setAgentId(sessionService.currentUserAgentId(request));
        } else {
            return JsonRet.buildRet(-97);
        }
        mfoyouServiceOrder.setServiceOrderId(orderId);
        ArrayListObject<HuawuServiceOrder> listObject = serviceOrderService.getServiceOrderList(mfoyouServiceOrder, null, null, null, null, null, null);
        if (listObject.size() == 1) {
            JSONObject ret = JSONMaker.AttachSubJsonString(listObject.get(0), "servicePayType");
            List<HuawuOrderLog> status = iOrder.getOrderLog(orderId, OrderType.serviceOrder.getValue());
            Date start = null;
            Date finsh = null;
            for (HuawuOrderLog mfoyouOrderLog : status) {
                if (mfoyouOrderLog.getOrderLogState() == OrderState.emServiceStart.getValue()) {
                    start = mfoyouOrderLog.getOrderLogTime();
                }
                if (mfoyouOrderLog.getOrderLogState() == OrderState.emServiceRunerFinsh.getValue()) {
                    finsh = mfoyouOrderLog.getOrderLogTime();
                }
            }
            if (finsh != null && start != null) {
                long value = finsh.getTime() - start.getTime();
                ret.put("taskDuration", value / 1000);
            }
            ret.put("flowList", JSON.toJSON(status));
            Integer wokerId = listObject.get(0).getServiceOrderReceiveUser();
            if (wokerId != null) {
                ret.putAll(runnerService.getWorkKeysInfo(wokerId, new String[]{"userName", "userHeadUrl", "userPhone", "workerCommentCount", "workerName", "workerPhone", "workerStar", "userNickName",
                        "workerOrderCount", "workerServiceDistance", "workerLong", "workerLat"}));
            }
            return JsonRet.buildSuccRet(ret);
        }
        return JsonRet.buildRet(-98);
    }

    /**
     * 普通用户撤销订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param weiToken
     * @return
     */
    @POST
    @Path(value = "/revoke/order/{orderId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> revokeOrder(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("orderId") Integer orderId, @QueryParam("key") String weiToken) {
        logger.info("begin revokeOrder orderId=" + orderId);
        Integer userId = sessionService.currentUserId(request);
        if (userId == null && weiToken == null) {
            return JsonRet.buildRet(-50);
        }
        if (weiToken != null && weiToken.equals(StringUtils.getSecrteString())) {
            logger.info("远程调用，orderid " + orderId);
            userId = 0;
        }
        HuawuServiceOrder mfoyouServiceOrder = iOrder.getServiceOrderInfo(orderId);
        if ((mfoyouServiceOrder.getServiceOrderState() >= OrderState.emRunerAccept.getValue()) || (!userId.equals(mfoyouServiceOrder.getServiceOrderSendUser())
                && userId.intValue() != 0)) {
            return JsonRet.buildRet(-95);
        }
        String revokeOrder = revokeOrder(mfoyouServiceOrder);
        if (revokeOrder != null) {
            return JsonRet.buildFailRet(revokeOrder);
        }
        Boolean bRet = serviceOrderService.revokeServiceOrder(orderId, mfoyouServiceOrder.getServiceOrderSendUser(), mfoyouServiceOrder.getServiceOrderPayAmount(), mfoyouServiceOrder.getServiceOrderState(),
                0, OrderState.emServiceRevoke.getValue());
        geoService.removeOrderPos("" + orderId);
        logger.info("fish revokeOrder bRet=" + bRet);
        if (!bRet) {
            return JsonRet.buildRet(-100);
        }
        logger.info("fish paybackOrder ");
        return JsonRet.buildRet(0);

    }

    /**
     * 代理商撤销订单
     *
     * @param request
     * @param response
     * @param orderId
     * @return
     */
    @POST
    @Path(value = "/revokeAgent/order/{orderId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> agentrevokeOrder(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("orderId") Integer orderId) {
        logger.info("agent begin revokeOrder orderId=" + orderId);
        Integer agentId = sessionService.currentUserId(request);
        HuawuServiceOrder mfoyouServiceOrder = iOrder.getServiceOrderInfo(orderId);
        if ((mfoyouServiceOrder.getServiceOrderState() >= OrderState.emServiceRunerFinsh.getValue()) || !mfoyouServiceOrder.getAgentId().equals(agentId)) {
            return JsonRet.buildRet(-95);
        }
        String revokeOrder = revokeOrder(mfoyouServiceOrder);
        if (revokeOrder != null) {
            return JsonRet.buildFailRet(revokeOrder);
        }
        Boolean bRet = serviceOrderService.revokeServiceOrder(orderId, mfoyouServiceOrder.getServiceOrderSendUser(), mfoyouServiceOrder.getServiceOrderPayAmount(), mfoyouServiceOrder.getServiceOrderState(),
                0, OrderState.emServiceRevoke.getValue());
        geoService.removeOrderPos("" + orderId);
        if (!bRet) {
            return JsonRet.buildRet(-100);
        }
        return JsonRet.buildRet(0);
    }

    /**
     * 筛选订单列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param service_order_type
     * @param serviceTagId
     * @param smallType
     * @param serviceOrderState
     * @param runnerId
     * @param isNew
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "square/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.RUNERACCESS})
    public JsonRet<?> squarelist(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
                                 @QueryParam("type") Integer service_order_type, @QueryParam("tagId") Integer serviceTagId, @QueryParam("smalltype") Integer smallType,
                                 @QueryParam("state") Integer[] serviceOrderState, @QueryParam("runerId") Integer runnerId, @QueryParam("isNew") Integer isNew) throws ParseException {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderType(service_order_type);
        mfoyouServiceOrder.setServiceTagId(serviceTagId);
        mfoyouServiceOrder.setServiceOrderSmallType(smallType);
        mfoyouServiceOrder.setServiceOrderReceiveUser(runnerId);
        mfoyouServiceOrder.setAgentId(sessionService.currentUserAgentId(request));
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = start == null ? null : DateUtils.date_sdf.parse(start);
        Date endDate = end == null ? null : DateUtils.date_sdf.parse(end);
        Integer loginType = sessionService.currentUserType(request);
        if (loginType == null) {
            loginType = 4;
        }
        long hashValue = 0;
        if (isNew != null && isNew.intValue() == 1) {
            hashValue = 1;
            mfoyouServiceOrder.setServiceOrderReceiveUser(sessionService.currentUserId(request));
        }
        //接单员
        if (loginType == 4) {
            HuawuWorker mfoyouWorkerInfo = iAccount.getWorkerInfo(sessionService.currentUserId(request));
            if (mfoyouWorkerInfo.getWorkerState() == -1) {
                return JsonRet.buildRet(-54);
            }
            Integer agentId = sessionService.currentUserAgentId(request);
            Integer stationId = sessionService.currentUserStationId(request);
            if (agentId == null) {
                agentId = 0;
            }
            mfoyouServiceOrder.setAgentId(agentId);
            mfoyouServiceOrder.setStationId(stationId);
        }
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        calculateOrderLonAndLat(request, mfoyouServiceOrder, lon, lat);
        List<Integer> states = null;
        if (serviceOrderState != null && serviceOrderState.length > 0) {
            states = new ArrayList<>();
            for (Integer state : serviceOrderState) {
                states.add(state);
            }
        }
        ArrayListObject<HuawuServiceOrder> listObject = serviceOrderService.getServiceOrderSquareList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, loginType, states, hashValue);
        //计算当前用户如果抢到单被提成的金额
        MfoyouCommonUtil.calcOrderPercentage(listObject, sessionService.currentWorkFee(request));
        return JsonRet.buildSuccRet(ListObject.BulidListObject(listObject));

    }

    /**
     * 跑腿小哥订单分页列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param serviceOrderType
     * @param serviceTagId
     * @param smallType
     * @param serviceOrderState
     * @param isNew
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/runer/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.RUNERACCESS)
    public JsonRet<?> runerList(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
                                @QueryParam("type") Integer serviceOrderType, @QueryParam("tagId") Integer serviceTagId, @QueryParam("smalltype") Integer smallType,
                                @QueryParam("state") Integer[] serviceOrderState, @QueryParam("isNew") Integer isNew) {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderReceiveUser(sessionService.currentUserId(request));
        mfoyouServiceOrder.setServiceOrderType(serviceOrderType);
        mfoyouServiceOrder.setServiceTagId(serviceTagId);
        mfoyouServiceOrder.setServiceOrderSmallType(smallType);
        Date startDate = DateUtils.parse(request.getParameter("startDate"));
        Date endDate = DateUtils.parse(request.getParameter("endDate"));
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        int flag = 1;
        if (isNew != null && isNew.intValue() == 1) {
            calculateOrderLonAndLat(request, mfoyouServiceOrder, lon, lat);
            HuawuWorker mfoyouWorker = iAccount.getWorkerInfo(sessionService.currentUserId(request));
            if (mfoyouWorker != null) {
                if (mfoyouWorker.getAgentId() == null) {
                    return JsonRet.buildRet(-2001);
                }
                mfoyouServiceOrder.setAgentId(mfoyouWorker.getAgentId());
            }
            flag = 4;
        }
        ArrayListObject<HuawuServiceOrder> listObject = iOrder.getServiceOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, ObjectUtil.arrary2List(serviceOrderState), flag);
        for (HuawuServiceOrder huawuServiceOrder : listObject) {
            if (huawuServiceOrder.getServiceRunnerAmount() != -1) huawuServiceOrder.reChangePayAmount();
            huawuServiceOrder.setServiceOrderAmount(huawuServiceOrder.getServiceOrderPayAmount());
        }
        return JsonRet.buildSuccRet(ListObject.BulidListObject(listObject));
    }

    /**
     * 代理商订单分页列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param service_order_type
     * @param service_tagId
     * @param smalltype
     * @param serviceOrderState
     * @param runerId
     * @param orderNumber
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "agent/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> agentlist(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
                                @QueryParam("type") Integer service_order_type, @QueryParam("tagId") Integer service_tagId, @QueryParam("smalltype") Integer smalltype,
                                @QueryParam("state") Integer[] serviceOrderState, @QueryParam("runerId") Integer runerId, @QueryParam("orderNum") String orderNumber) throws ParseException {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderType(service_order_type);
        mfoyouServiceOrder.setServiceTagId(service_tagId);
        mfoyouServiceOrder.setServiceOrderSmallType(smalltype);
        mfoyouServiceOrder.setServiceOrderReceiveUser(runerId);
        mfoyouServiceOrder.setServiceOrderNumber(orderNumber);
        String source = request.getParameter("source");
        if (source != null) {
            mfoyouServiceOrder.setServiceOrderSource(Integer.parseInt(source));
        }
        if (sessionService.currentUserType(request).intValue() == UserRight.AGENTACCESS.getValue()) {
            mfoyouServiceOrder.setAgentId(sessionService.currentUserId(request));
        } else {
            mfoyouServiceOrder.setStationId(sessionService.currentUserId(request));
        }
        String start = request.getParameter("sdate");
        String end = request.getParameter("edate");
        Date startDate = start == null ? null : DateUtils.date_sdf.parse(start);
        Date endDate = end == null ? null : DateUtils.date_sdf.parse(end);
        ArrayListObject<HuawuServiceOrder> listObject = iOrder.getServiceOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, ObjectUtil.arrary2List(serviceOrderState), null);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(serviceOrderService.attachWorkerInfo(listObject, null)));
    }

    @GET
    @Path(value = "getAllOrderCount")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> getAllOrderCount(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        int type = sessionService.currentUserType(request).intValue() == 2 ? 0 : 1;
        Map<String, Object> allOrderCount = serviceOrderService.getAllOrderCount(sessionService.currentUserId(request), type);
        return JsonRet.buildSuccRet(allOrderCount);
    }

    @GET
    @Path(value = "getCanUseCoupon")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.LOGINACCESS)
    public JsonRet<?> getCanUseCoupon(@Context HttpServletRequest request,
                                      @QueryParam("agentId") Integer agentId, @QueryParam("typeName") String typeName) {
        Integer userId = sessionService.currentUserId(request);
        List<HuawuServiceCoupon> canUseCoupon = serviceOrderService.getCanUseCouponV2(agentId, typeName, userId);
        return JsonRet.buildSuccRet(canUseCoupon);
    }

    @GET
    @Path(value = "abnormalOrder")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.RUNERACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> urgeAbnormal(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize,
                                   @QueryParam("runerId") Integer runerId) throws ParseException {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderReceiveUser(runerId);
        mfoyouServiceOrder.setAgentId(sessionService.currentUserAgentId(request));
        Integer loginType = sessionService.currentUserType(request);
        if (loginType.intValue() == MfoyouUserType.runer.getValue()) {
            mfoyouServiceOrder.setServiceOrderReceiveUser(sessionService.currentUserId(request));
        } else if (loginType.intValue() == MfoyouUserType.agent.getValue()) {
            mfoyouServiceOrder.setAgentId(sessionService.currentUserId(request));
        } else {
            mfoyouServiceOrder.setAgentId(sessionService.currentUserAgentId(request));
            mfoyouServiceOrder.setStationId(sessionService.currentUserId(request));
        }
        String source = request.getParameter("source");
        if (source != null) {
            mfoyouServiceOrder.setServiceOrderSource(Integer.parseInt(source));
        }
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = start == null ? null : DateUtils.date_sdf.parse(start);
        Date endDate = end == null ? null : DateUtils.date_sdf.parse(end);
        String type = request.getParameter("type");
        ArrayListObject<HuawuServiceOrder> listObject = serviceOrderService.getAbnormalOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, type);
        return JsonRet.buildSuccRet(ListObject.BulidListObject(
                serviceOrderService.attachWorkUserInfo(listObject, new String[]{"userName", "userHeadUrl", "userPhone", "workerCommentCount", "workerName", "workerPhone", "workerStar", "userNickName", "userId"})));
    }

    /**
     * 计算订单经纬度
     *
     * @param request
     * @param mfoyouServiceOrder
     * @param lon
     * @param lat
     */
    private void calculateOrderLonAndLat(@Context HttpServletRequest request, HuawuServiceOrder mfoyouServiceOrder, String lon, String lat) {
        if (lon != null && lat != null) {
            mfoyouServiceOrder.setServiceUserLon(StrUtil.parseDouble(lon));
            mfoyouServiceOrder.setServiceUserLat(StrUtil.parseDouble(lat));
        } else {
            Map<String, String> map = redisCacheManger.getMapValue("u:" + sessionService.currentUserId(request));
            if (map != null && map.get("lon") != null && map.get("lat") != null) {
                mfoyouServiceOrder.setServiceUserLon(StrUtil.parseDouble(map.get("lon")));
                mfoyouServiceOrder.setServiceUserLat(StrUtil.parseDouble(map.get("lat")));
            } else if (sessionService.currentUserlat(request) != null && sessionService.currentUserlon(request) != null) {
                mfoyouServiceOrder.setServiceUserLon(sessionService.currentUserlon(request));
                mfoyouServiceOrder.setServiceUserLat(sessionService.currentUserlat(request));
            }
        }
    }

    /**
     * 撤销订单公共方法
     *
     * @param mfoyouServiceOrder
     * @return
     */
    private String revokeOrder(HuawuServiceOrder mfoyouServiceOrder) {
        if (mfoyouServiceOrder.getServiceOrderSource() != null && mfoyouServiceOrder.getServiceOrderSource() == 1) {
            MfoyouGoodsOrder mfoyouGoodsOrder = new MfoyouGoodsOrder();
            mfoyouGoodsOrder.setOrderId(mfoyouServiceOrder.getServiceOrderSourceId());
            return iOrder.revokeServiceOrderToGoodsOrder(mfoyouServiceOrder.getServiceOrderSourceId()) == 1 ? null : "更新数据库失败";
        }
        HuawuPay mfoyoupay = new HuawuPay();
        mfoyoupay.setPayOrderType(OrderType.serviceOrder.getValue());
        mfoyoupay.setPayOrderId(mfoyouServiceOrder.getServiceOrderId());
        List<HuawuPay> listObject = paymentService.getCanBeRevokeList(mfoyoupay, Arrays.asList(1, 3));
        for (HuawuPay mfoyouPay : listObject) {
            int payType = mfoyouPay.getPayType();
            String ret = null;
            if (payType == 2) {
                //微信
                ret = wxBaseService.refundPay(mfoyouServiceOrder.getAgentId(), mfoyouPay.getPayAppId(), mfoyouPay.getPayNumber(), mfoyouPay.getPayAmount());
                if (ret != null) {
                    return ret;
                }
                paymentService.addStream(mfoyouServiceOrder.getServiceOrderSendUser(), mfoyouPay.getPayAmount(), 1, mfoyouServiceOrder.getServiceOrderId(), OrderType.serviceOrder.getValue(), PayType.serviceOrder.getValue(),
                        PayType.WeChat.getValue(), "服务订单撤销", MfoyouUserType.customer.getValue());
                if (ret == null) {
                    redisCacheManger.pushRList(SERVICE_ORDER_REVOKE, mfoyouServiceOrder.getServiceOrderId() + "");
                }
            } else if (mfoyouPay.getPayType() == PayType.wallet.getValue()) {
                //第三方订单
                ret = paymentService.returnBackFreignMoney(mfoyouServiceOrder.getServiceOrderSendUser(), mfoyouPay.getPayAmount());
                paymentService.addStream(mfoyouServiceOrder.getServiceOrderSendUser(), mfoyouPay.getPayAmount(), 1, mfoyouServiceOrder.getServiceOrderId(), OrderType.serviceOrder.getValue(), PayType.wallet.getValue(),
                        PayType.wallet.getValue(), "服务钱包订单撤销", MfoyouUserType.customer.getValue());
                if (ret == null) {
                    redisCacheManger.pushRList(SERVICE_ORDER_REVOKE, mfoyouServiceOrder.getServiceOrderId() + "");
                } else {
                    logger.info("fail");
                }
            } else {
                logger.error("未知的支付类型" + JSON.toJSONString(mfoyouPay));
            }
            HuawuPay savePay = new HuawuPay();
            savePay.setPayId(mfoyouPay.getPayId());
            savePay.setPayState(ret == null ? CommonState.emauitSucess.getValue() : CommonState.emauitfail.getValue());
            paymentService.modifyMfoyouPay(savePay);
        }
        return null;
    }
}
